package com.usoft.thrift.monitor;

import com.usoft.thrift.server.ThriftServiceServerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by xinxingegeya on 16/3/5.
 */
@Component
public class ServiceMonitorInfoEndpoint implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    /**
     * 获取所有的监控信息
     * 
     * @return
     */
    public Map<String, ServiceMonitorInfo> exposeMonitorInfo() {
        Map<String, ThriftServiceServerFactory> map = applicationContext
            .getBeansOfType(ThriftServiceServerFactory.class);
        Map<String, ServiceMonitorInfo> info = new HashMap<>();
        for (Map.Entry<String, ThriftServiceServerFactory> entry : map
            .entrySet()) {
            info.put(entry.getKey(), entry.getValue().getMonitorInfo());
        }
        return info;
    }

    /**
     * 根据服务名,全限定名,得到服务的运行信息
     * 
     * @param serviceName
     * @return
     */
    public ServiceMonitorInfo exposeMonitorInfoByServiceName(
            String serviceName) {
        if (!StringUtils.isEmpty(serviceName)) {
            return null;
        }
        Map<String, ThriftServiceServerFactory> map = applicationContext
            .getBeansOfType(ThriftServiceServerFactory.class);
        for (Map.Entry<String, ThriftServiceServerFactory> entry : map
            .entrySet()) {
            if (entry.getKey().equals(serviceName)) {
                return entry.getValue().getMonitorInfo();
            }
        }
        return null;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext)
            throws BeansException {
        this.applicationContext = applicationContext;
    }
}
